package com.xiejr.pss.jvm.classloader;

import java.io.File;
import java.io.FileInputStream;


/**
 * 演示自定义类加载器加载外部磁盘文件中的字节码文件
 *
 * @author mobai
 * @since 2021/5/20 11:37
 */
public class MyClassLoader extends ClassLoader {

    private final String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) {
        try {
            byte[] bytes = loadByte(name);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public byte[] loadByte(String name) throws Exception {
        name = name.replace(".", "/");
        FileInputStream fileInputStream = new FileInputStream(classPath + File.separator + name + ".class");
        byte[] result = new byte[fileInputStream.available()];
        fileInputStream.read(result);
        fileInputStream.close();
        return result;
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        MyClassLoader myClassLoader = new MyClassLoader("/Users/mobai/Desktop");
        Class<?> aClass = myClassLoader.loadClass("com.xiejr.pss.jvm.classloader.TestJdkClassLoader");
        //只有调用new、调用静态方法、.静态属性才会触发初始化
        aClass.newInstance();
        System.out.println(aClass.getClassLoader());
    }
}
